﻿using BCCommon;
using BCCommon.Enums;
using BCData.Sim.Company.Company;
using BCData.TMS.Agent.AgentRecord;
using BCDto.Common.Remark;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.Agent.AgentRecord;
using BCEntity.Common.EntityNameConst;
using BCEntity.TMS.Agent.AgentRecord;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCService.TMS.Agent.AgentRecord
{
    public class AgentRecordService : IAgentRecordService
    {
        private readonly IAgentRecordData agentRecordData;
        private readonly ICompanyData companyData;
        private readonly IDatabaseContext databaseContext;
        private readonly IRedisService redisService;
        private readonly string key = string.Format("{0}", EntityNameConst.AgentRecordEntity);
        private readonly string viewKey = string.Format("{0}", EntityNameConst.AgentRecordViewEntity);
        public AgentRecordService(IAgentRecordData agentRecordData,
            ICompanyData companyData,
            IDatabaseContext databaseContext,
            IRedisService redisService)
        {
            this.agentRecordData = agentRecordData;
            this.companyData = companyData;
            this.databaseContext = databaseContext;
            this.redisService = redisService;
        }

        public AgentRecordDto Add(AdminDto admin, AgentRecordRequestDto requestDto)
        {
            //if (requestDto.AgentLevel <= 0)
            //{
            //    throw new ArgumentException("代理商级别不能为空");
            //}
            ////if (requestDto.CompanyId <= 0)
            ////{
            ////    throw new ArgumentException("公司不能为空");
            ////}
            //if (requestDto.ParentCompanyId <= 0)
            //{
            //    throw new ArgumentException("父级公司不能为空");
            //}
            ////var companyEntity = this.companyData.GetEntity(requestDto.CompanyId).Result;
            ////if (companyEntity == null)
            ////{
            ////    throw new ArgumentException("公司信息不存在");
            ////}
            //companyEntity = this.companyData.GetEntity(requestDto.ParentCompanyId).Result;
            //if (companyEntity == null)
            //{
            //    throw new ArgumentException("父级公司信息不存在");
            //}
            ////var result = this.agentRecordData.GetEntityByCompanyId(requestDto.CompanyId).Result;
            ////if (result != null)
            ////{
            ////    throw new ArgumentException("此公司已有代理商信息");
            ////}
            //result = this.agentRecordData.GetEntityByCompanyId(requestDto.ParentCompanyId).Result;
            //return this.agentRecordData.Insert(new AgentRecordEntity()
            //{
            //    CompanyId = requestDto.CompanyId,
            //    AgentLevel = requestDto.AgentLevel,
            //    ParentCompanyId = requestDto.ParentCompanyId,
            //    CompanyPathCode = result == null ? $"{requestDto.ParentCompanyId},{requestDto.CompanyId}" : $"{result.CompanyPathCode},{requestDto.CompanyId}",
            //    CreateAdminId = admin.AdminId,
            //    CreateAdminName = admin.FullName,
            //    CreateTime = DateTime.Now,
            //    UpdateTime = DateTime.Now,
            //    EditAdminId = admin.AdminId,
            //    EditAdminName = admin.FullName
            //}).GetAwaiter().GetResult().As<AgentRecordDto>();
            return null;
        }

        public void Delete(AdminDto admin, long agentRecordId, RemarkRequestDto remarkRequestDto)
        {
            var result = this.agentRecordData.GetEntity(agentRecordId).Result;
            if (result == null)
            {
                throw new ArgumentException("代理商信息不存在");
            }
            if (admin.CompanyId != 1 && admin.CompanyId != result.ParentCompanyId)
            {
                throw new ArgumentException("您无权限操作此记录");
            }
            result.UpdateTime = DateTime.Now;
            result.EditAdminId = admin.AdminId;
            result.EditAdminName = admin.FullName;
            this.agentRecordData.Update(result).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            this.redisService.DeleteMultipleKey(viewKey, false);
        }

        public AgentRecordDto Get(AdminDto adminDto)
        {
            return this.agentRecordData.GetEntityByCompanyId(adminDto.CompanyId).Result.As<AgentRecordDto>();
        }
        public AgentRecordDto Get(long agentRecordId)
        {
            string cacheKey = this.redisService.GetKey(key, agentRecordId);
            var result = this.redisService.TryGet(cacheKey,() =>
            {
                return this.agentRecordData.GetEntity(agentRecordId).Result.As<AgentRecordDto>();
            }, TimeSpan.FromDays(1));
            return result;
        }

        public AgentRecordDto GetByCompanyId(int companyId)
        {
            return this.agentRecordData.GetEntityByCompanyId(companyId).Result.As<AgentRecordDto>();
        }

        public PageableList<AgentRecordViewDto> Query(AdminDto admin, int? companyId, int? parentCompanyId, int? agentLevel, bool? isDelete, DateTime? createStartDate, DateTime? createEndDate, CompanyBusinessType? businessType, string companyName, int pageIndex, int pageSize)
        {
            int? logonCmpanyId = admin.CompanyId;
            if (admin.CompanyId == 1)
            {
                logonCmpanyId = null;
            }
            string cacheKey = this.redisService.GetKey(key, logonCmpanyId, companyId, parentCompanyId, agentLevel, isDelete, createStartDate, createEndDate, businessType, companyName, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
             {
                 var (data, dataCount) = this.agentRecordData.Query(logonCmpanyId, companyId, parentCompanyId, agentLevel, isDelete, createStartDate, createEndDate, businessType, companyName, pageIndex, pageSize).Result;
                 return new PageableList<AgentRecordViewDto>()
                 {
                     Count = dataCount,
                     Items = data.As<List<AgentRecordViewDto>>(),
                     PageIndex = pageIndex,
                     PageSize = pageSize
                 };
             }, TimeSpan.FromDays(1));
            return result;
        }

        public AgentRecordDto Update(AdminDto admin, long agentRecordId, AgentRecordPutDto putDto)
        {
            if (putDto.AgentLevel <= 0)
            {
                throw new ArgumentException("代理商级别不能为空");
            }
            if (putDto.ParentCompanyId <= 0)
            {
                throw new ArgumentException("父级公司不能为空");
            }
            var result = this.agentRecordData.GetEntity(agentRecordId).Result;
            if (result == null)
            {
                throw new ArgumentException("代理商信息不存在");
            }
            if (admin.CompanyId != 1 && admin.CompanyId != result.ParentCompanyId)
            {
                throw new ArgumentException("您无权限操作此记录");
            }
            var companyEntity = this.companyData.GetEntity(putDto.ParentCompanyId).Result;
            if (companyEntity == null)
            {
                throw new ArgumentException("父级公司信息不存在");
            }
            var parentResult = this.agentRecordData.GetEntityByCompanyId(putDto.ParentCompanyId).Result;
            result.AgentLevel = putDto.AgentLevel;
            result.ParentCompanyId = putDto.ParentCompanyId;
            result.CompanyPathCode = parentResult == null ? $"{putDto.ParentCompanyId},{result.CompanyId}" : $"{parentResult.CompanyPathCode},{result.CompanyId}";
            result.UpdateTime = DateTime.Now;
            result.EditAdminId = admin.AdminId;
            result.EditAdminName = admin.FullName;
            this.agentRecordData.Update(result).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            this.redisService.DeleteMultipleKey(viewKey, false);
            return result.As<AgentRecordDto>();
        }

        public AgentRecordDto UpdateManualAssign(AdminDto admin, long agentRecordId, AgentRecordManualAssignDto putDto)
        {
            var result = this.agentRecordData.GetEntity(agentRecordId).Result;
            if (result == null)
            {
                throw new ArgumentException("代理商信息不存在");
            }
            if (admin.CompanyId != 1 && admin.CompanyId != result.CompanyId)
            {
                throw new ArgumentException("您无权限操作此记录");
            }
            result.EnabledManualAssign = putDto.EnabledManualAssign;
            if (putDto.ManualAssignWaitTime.HasValue)
            {
                result.ManualAssignWaitTime = putDto.ManualAssignWaitTime.Value;
            }
            result.UpdateTime = DateTime.Now;
            result.EditAdminId = admin.AdminId;
            result.EditAdminName = admin.FullName;
            this.agentRecordData.Update(result).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            this.redisService.DeleteMultipleKey(viewKey, false);
            return result.As<AgentRecordDto>();
        }

        public AgentRecordViewDto GetViewByAgentRecordId(long agentRecordId)
        {
            string cacheKey = this.redisService.GetKey(viewKey, agentRecordId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                return this.agentRecordData.GetViewByAgentRecordIdAsync(agentRecordId).Result.As<AgentRecordViewDto>();
            }, TimeSpan.FromDays(1));
            return result;

        }

        public AgentRecordDto GetById(long agentRecordId)
        {
            var result = this.agentRecordData.GetEntity(agentRecordId).Result;
            return result.As<AgentRecordDto>();
        }
    }
}
